package cracker.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class NetClient {

	private static BufferedReader br=null;
	private static PrintWriter pw=null;
	private Address home;
	private String clientName;
	private Scanner scanner = new Scanner(System.in);
	private static Socket socket = null;
	private void setUp() {
		
		try {
			socket = new Socket("localhost",10880);
			br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			pw = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
			pw.append(home.toString()+"\n");
			pw.append("name:"+clientName+"\n");
			pw.flush();
			new RequestThread(pw).start();
			new ResponseThread(br).start();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public NetClient(String ip,int port,String clientName) {
		Address address = new Address();
		address.setHost(ip);
		address.setPort(port);
		this.home = address;
		this.clientName = clientName;
	}
	
	class RequestThread extends Thread {
	
		private PrintWriter pw = null;
		
		public RequestThread(PrintWriter pw) {
			this.pw = pw;
		}

		@Override
		public void run() {
			while(scanner.hasNext()) {
				pw.append(scanner.nextLine()+"\n");
				pw.flush();
			}
		}
	}
	
	class ResponseThread extends Thread {
		
		private BufferedReader br = null;
		
		public ResponseThread(BufferedReader br) {
			this.br = br;
		}
		
		@Override
		public void run() {
			while(true){
				String string;
				try {
					string = br.readLine();
					if(string==null || string.equals("exit")){
						break;
					} else
						System.out.println(Thread.currentThread().getName()+" client读到："+string);
				} catch (IOException e) {
					e.printStackTrace();
				}   
			}
		}
	}
	
	public static void main(String[] args) {
		for(int i=0;i<100;i++) {
			NetClient client = new NetClient("192.168.0."+i, 11, "job_"+i);
			client.setUp();
		}
	}
}
